package com.itbupt.eat.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itbupt.eat.common.R;
import com.itbupt.eat.entity.Employee;
import com.itbupt.eat.service.IEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @Author BUPT-Dingchang
 * @Create 2024/4/20 21:55
 * ClassName: EmployeeController
 * Description:
 */

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    // 注入业务层
    @Autowired
    private IEmployeeService employeeService;

    /**
     * 后台员工登录方法
     * @param request 请求对象
     * @param employee 员工对象
     * @return R
     */
    @RequestMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        String username = employee.getUsername();
        String password = employee.getPassword();
        // 1. 对传入的密码进行MD5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        // 2. 根据用户名和密码查询员工
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Strings.isNotEmpty(username), Employee::getUsername, username);

        Employee emp = employeeService.getOne(queryWrapper);

        // 3. 判断员工是否存在
        if (emp == null) {
            return R.error("用户不存在, 登录失败！");
        }

        // 4. 判断密码是否正确
        if(!password.equals(emp.getPassword())) {
            return R.error("密码错误, 登录失败！");
        }

        // 5. 查看员工状态是否禁用
        if(emp.getStatus() != 1) {
            return R.error("用户已被禁用, 登录失败！");
        }

        // 6. 登录成功---将员工ID存放在Session保存作用域中
        request.getSession().setAttribute("employee", emp.getId());

        return R.success(emp);
    }


    /**
     * 后台员工退出登录方法
     * @param request 请求对象
     * @return  R
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        // 1.清除Session保存作用域中保存的数据
        request.getSession().removeAttribute("employee");
        // 2.返回结果
        return R.success("退出成功");
    }


    /**
     * 后台员工添加方法
     * @param request 请求对象
     * @param employee  员工对象
     * @return  R
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {

        // 1.检验账号username是否已存在
        String username = employee.getUsername();
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, username);
        Employee emp = employeeService.getOne(lqw);
        if (emp != null) {
            return R.error("账号已存在，添加失败");
        }

        // 2.设置创建人ID
        //employee.setCreateUser((Long) request.getSession().getAttribute("employee"));

        // 3.设置最后修改人ID
        //employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));

        // 4.设置初始密码为身份证后6位，并经过MD5加密
        String idNumber = employee.getIdNumber();
        String password = DigestUtils.md5DigestAsHex(idNumber.substring(idNumber.length() - 6).getBytes());
        employee.setPassword(password);

        // 5.设置创建时间
        //employee.setCreateTime(LocalDateTime.now());

        // 6.设置创建时间
        //employee.setUpdateTime(LocalDateTime.now());

        // 7.调用业务层保存到数据库中
        employeeService.save(employee);
        return R.success("添加成功");
    }

    /**
     * 后台员工分页查询方法
     * @param page  当前页
     * @param pageSize  每页显示的条数
     * @param name  员工姓名
     * @return  R
     */
    @GetMapping("/page")
    public R<Page<Employee>> getPage(Long page, Long pageSize, String name) {
        return R.success(employeeService.getPage(page, pageSize, name));
    }

    ///**
    // * 修改员工信息
    // * @param request 请求对象
    // * @param employee 员工对象
    // * @return  R
    // */
    //@PutMapping
    //public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
    //    if(employeeService.update(request, employee)) {
    //        return R.success("修改成功");
    //    }
    //    return R.error("修改失败");
    //}
    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        if(employeeService.updateById(employee)) {
            return R.success(
                    "修改成功");
        }
        return R.error("修改失败");
    }

    /**
     * 根据id查询员工信息
     * @param id   员工ID
     * @return  R
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        // 当查询结果不为空时才返回employee
        if(employee != null) {
            return R.success(employee);
        }
        return R.error("员工不存在，查询失败");
    }



}
